package dao_base

import (
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_base"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetArticleGroupPageList(baseArticleGroup model_base.SelectBaseArticleGroup) (baseArticleGroups []model_base.BaseArticleGroupVo, total int64, err error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleGroupPo{})
	if baseArticleGroup.UserId != 0 {
		db = db.Where("user_id = ?", baseArticleGroup.UserId)
	}
	if baseArticleGroup.GroupName != "" {
		db = db.Where("group_name like ?", "%"+baseArticleGroup.GroupName+"%")
	}
	if baseArticleGroup.LibraryId != 0 {
		db = db.Where("library_id = ?", baseArticleGroup.LibraryId)
	}
	if baseArticleGroup.Status != "" {
		db = db.Where("status = ?", baseArticleGroup.Status)
	}
	if !baseArticleGroup.StartTime.IsZero() {
		db = db.Where("create_time >= ?", baseArticleGroup.StartTime)
	}
	if !baseArticleGroup.EndTime.IsZero() {
		db = db.Where("create_time <= ?", baseArticleGroup.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("create_time desc")
	if baseArticleGroup.PageNum != nil && baseArticleGroup.PageSize != nil {
		db = db.Limit(*baseArticleGroup.PageSize).Offset((*baseArticleGroup.PageNum - 1) * *baseArticleGroup.PageSize)
	} else {
		db = db.Limit(10)
	}
	err = db.Find(&baseArticleGroups).Error
	err = errs.ErrNotFound(err)
	return
}

func GetArticleGroupInfo(groupId int) (baseArticleGroup model_base.BaseArticleGroupVo, err error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleGroupPo{})
	err = db.Where("group_id = ? and deleted = '0'", groupId).First(&baseArticleGroup).Error
	err = errs.ErrNotFound(err)
	return
}

func AddArticleGroup(baseArticleGroup model_base.BaseArticleGroupPo) (int, error) {
	db := mysql.Db("salve-1")
	res := db.Create(&baseArticleGroup)
	return baseArticleGroup.GroupId, errs.ErrNotFound(res.Error)
}

func EditArticleGroup(baseArticleGroup model_base.BaseArticleGroupPo) (int64, error) {
	db := mysql.Db("salve-1")
	res := db.Updates(&baseArticleGroup)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveArticleGroup(groupIds []string, uk string) (int64, error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleGroupPo{})
	db.Where("group_id in (?)", groupIds)
	res := db.Updates(&model_base.BaseArticleGroupPo{BaseEntity: model.BaseEntity{UpdateTime: utils.NewTimeNow(), UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeletedArticleGroup(groupIds []string) (int64, error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleGroupPo{})
	db.Where("group_id in (?)", groupIds)
	res := db.Delete(&model_base.BaseArticleGroupPo{})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}
